const Service = require("egg").Service;

class UserOrder extends Service {
  // 添加订单
  async addOrder() {
    try {
      let order_no = new Date().getTime();
      let logistics = null;

      let {
        shop_id,
        userInfo_id,
        user_id,
        order_state = 0,
        quantity
      } = this.ctx.request.body;

      let obj = {
        shop_id,
        userInfo_id,
        user_id,
        order_no,
        order_state,
        logistics,
        quantity
      };

      let res = await this.app.model.Order.create(obj);

      if (!res)
        return {
          msg: "添加失败"
        };

      return {
        msg: "添加成功"
      };
    } catch (e) {
      console.log(e);
    }
  }

  // 修改订单状态 (用户未付款 0   用户付款 1  用户收货 2)
  async updateOrder() {
    let id = this.ctx.params.id;

    let { order_state } = this.ctx.request.body;

    if (order_state == 1 || order_state == 2 || order_state == 0) {
      let res = await this.app.model.Order.update(
        { order_state },
        {
          where: {
            id
          }
        }
      );

      if (!res) return { msg: "修改失败" };

      return {
        msg: "修改成功"
      };
    }
    return {
      msg: "订单的状态值只能是0 1 2"
    };
  }

  // 删除订单
  async deleteOrder() {
    let id = this.ctx.params.id;
    let res = await this.app.model.Order.destroy({ where: { id } });
    if (!res) return { msg: "删除失败" };

    return {
      msg: "删除成功"
    };
  }

  // 根据用户id查询用户的订单列表
  async queryOrderByUserId() {
    // let user_id = this.ctx.request.body.user_id;

    let url = this.ctx.request.url;

    let user_id = url.match(/=(\S*)/)[1];

    let res = await this.app.model.Order.findAll({
      where: {
        user_id
      },
      include: {
        model: this.app.model.Commodity,
        as: "shop"
      }
    });

    if (!res) return { msg: "查询失败" };

    return res;
  }

  // 根据订单id查询订单详情
  async queryOrderByOrderId() {
    // let id = this.ctx.request.body.id;

    let url = this.ctx.request.url;

    let id = url.match(/=(\S*)/)[1];

    let res = await this.app.model.Order.findAll({
      where: {
        id
      },
      include: [
        {
          model: this.app.model.UserInfo,
          as: "userInfo"
        },
        {
          model: this.app.model.Commodity,
          as: "shop"
        }
      ]
    });

    if (!res) return { msg: "查询失败" };

    return res;
  }

  // 根据 订单状态 和 用户id 查询 订单 （未付款，进行中，已收货）
  async queryOrderByOrderIdAndUserId() {
    // let { user_id, order_state } = this.ctx.request.body;

    let { user_id, order_state } = this.ctx.query;

    let res = await this.app.model.Order.findAll({
      where: {
        user_id,
        order_state
      },
      include: {
        model: this.app.model.Commodity,
        as: "shop"
      }
    });

    if (!res) return { msg: "查询失败" };

    return res;
  }
}

module.exports = UserOrder;
